// import { ListPosition } from '@/interface/virtualList';
import { defineComponent, computed, watchEffect, getCurrentInstance, ref, onMounted, nextTick, toRaw, reactive } from 'vue';
import './index.scss';
interface ListPosition {
	startIndex: number;
	endIndex: number;
}

export default defineComponent({
	props: {
		// 列表可视区域高度
		listHeight: {
			type: String,
			default() {
				return '500';
			},
		},
		// 渲染行数
		screenLineNum: {
			type: String,
			default() {
				return '30';
			},
		},
		// 列表项高度
		itemHeight: {
			type: String,
			default() {
				return '50';
			},
		},
		list: {
			type: Array,
			default() {
				return [];
			},
		},
	},
	setup(props, ctx) {
		const { proxy } = getCurrentInstance();

		watchEffect(() => {
			if (props.list.length) {
				nextTick(() => {
					const dom = toRaw(proxy.$refs.virtualList);
					// 数组不为空，监听scroll事件
					dom.addEventListener('scroll', handleScroll);
				});
			}
		});

		const showObj = reactive<ListPosition>({
			startIndex: 0,
			endIndex: Number(props.listHeight) / Number(props.itemHeight),
		});

		// 滚动条监听
		const handleScroll = (event: Event): void => {
			const target = event.target as Element;
			showObj.startIndex = Math.floor(target.scrollTop / Number(props.itemHeight)); // 开始下标
			showObj.endIndex = Math.floor(target.scrollTop / Number(props.itemHeight)) + Number(props.listHeight) / Number(props.itemHeight);
		};

		// 模拟高度
		const boxHeight = computed(() => {
			return { height: `${props.list.length * Number(props.itemHeight)}px` };
		});

		// 保证内容在滚动区域内，增加paddingtop
		const paddingTop = computed(() => {
			return { paddingTop: `${showObj.startIndex * Number(props.itemHeight)}px` };
		});

		// 当前现实的列表内容
		const showList = computed(() => {
			if (props.list.length > 0) {
				return props.list.slice(showObj.startIndex, showObj.endIndex);
			}
			return [];
		});
		return () => (
			<div class="virtualList" ref="virtualList" style={{ height: `${props.listHeight}px` }}>
				<div class="virtualList-scroll" style={{ ...boxHeight.value, ...paddingTop.value }}>
					{showList.value.map((item) => (
						<div style={{ height: `${props.itemHeight}px` }}>{item}</div>
					))}
				</div>
			</div>
		);
	},
});
